package com.zhiwang.xiaoqu.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.LevelListDrawable
import android.view.Gravity
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat

class SelectableTab : LinearLayout {

    private var iconImageView: ImageView
    private var titleTextView: TextView

    var tabSelected: Boolean = false

    private var tabSelectedColor: Int = 0
    private var tabUnselectedColor: Int = 0

    private var tabSelectedIcon: Drawable
    private var tabUnselectedIcon: Drawable


    constructor (context: Context, tabParam: ArcTabBar.TabParam) : super(context) {
        tabSelectedColor = ContextCompat.getColor(context, tabParam.selectedTextColorRes)
        tabUnselectedColor = ContextCompat.getColor(context, tabParam.unSelectedTextColorRes)
        tabSelectedIcon = ContextCompat.getDrawable(context, tabParam.selectedIconRes)!!
        tabUnselectedIcon = ContextCompat.getDrawable(context, tabParam.unselectedIconRes)!!


        orientation = VERTICAL

        val ivLp = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
        ivLp.gravity = Gravity.CENTER_HORIZONTAL
        iconImageView = ImageView(context)
        val levelImage = LevelListDrawable()
        levelImage.addLevel(1, 1, tabUnselectedIcon)
        levelImage.addLevel(2, 2, tabSelectedIcon)
        levelImage.setBounds(0, 0, tabSelectedIcon.intrinsicWidth, tabSelectedIcon.intrinsicHeight)
        iconImageView.setImageDrawable(levelImage)
        iconImageView.setImageLevel(1)

        val tvLp = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
        tvLp.gravity = Gravity.CENTER_HORIZONTAL

        titleTextView = TextView(context)
        titleTextView.setTextColor(tabUnselectedColor)
        titleTextView.text = tabParam.text
        titleTextView.textSize = tabParam.tabTextSizeSp
        addView(iconImageView, ivLp)
        addView(titleTextView, tvLp)


    }


    fun select() {
        tabSelected = true
        invalidateTabIcon()
        invalidateTextColor()
    }


    fun toggle() {
        tabSelected = tabSelected.not()
        invalidateTabIcon()
        invalidateTextColor()
    }

    private fun invalidateTextColor() {
        if (tabSelected)
            titleTextView.setTextColor(tabSelectedColor)
        else titleTextView.setTextColor(tabUnselectedColor)
    }

    private fun invalidateTabIcon() {
        val levelImage = iconImageView.drawable as LevelListDrawable
        levelImage.level = if (tabSelected) 2 else 1
    }

    fun unselect() {
        tabSelected = false
        invalidateTabIcon()
        invalidateTextColor()
    }


}